import 'package:universal_io/io.dart';

import 'package:flutter/material.dart';
//import 'package:geocoding/geocoding.dart';
import 'package:macless_haystack/accessory/accessory_icon.dart';
import 'package:macless_haystack/accessory/accessory_model.dart';
import 'package:macless_haystack/location/location_model.dart';
import 'package:intl/intl.dart';
import 'accessory_battery.dart';
import 'package:macless_haystack/location/place_info.dart';

LocationModel locationModel = LocationModel();

class AccessoryListItem extends StatelessWidget {
  /// The accessory to display the information for.
  final Accessory accessory;

  /// A trailing distance information widget.
  final Widget? distance;

  /// Address information about the accessories location.
  final Placeinfo? herePlace;
  final VoidCallback onTap;
  final VoidCallback? onLongPress;

  /// Displays the location of an accessory as a concise list item.
  ///
  /// Shows the icon and name of the accessory, as well as the current
  /// location and distance to the user's location (if known; `distance != null`)
  const AccessoryListItem({
    super.key,
    required this.accessory,
    required this.onTap,
    this.onLongPress,
    this.distance,
    this.herePlace,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<Placeinfo?>(
      future: accessory.place,
      builder: (BuildContext context, AsyncSnapshot<Placeinfo?> snapshot) {
        // Format the location of the accessory. Use in this order:
        //   * Address if known
        //   * Coordinates (latitude & longitude) if known
        //   * `Unknown` if unknown
        var converted = locationModel.wgs84ToGcj02(accessory.lastLocation);
        String locationString = converted != null
            ? '${converted!.latitude.toStringAsFixed(4)}, ${converted!.longitude.toStringAsFixed(4)}'
            : 'Unknown';
        if (snapshot.hasData && snapshot.data != null) {
          Placeinfo place = snapshot.data!;
          if (place.name != null && place.name!.isNotEmpty) {
            locationString = '${place.name}';
          } else {
            locationString =
                '${place.province ?? ''}${place.city ?? ''}${place.district ?? ''}${place.township ?? ''}${place.street ?? ''}';
          }
        }
        // Format published date in a human readable way
        String? dateString = accessory.datePublished != null &&
                accessory.datePublished != DateTime(1970)
            ? ' · ${DateFormat('MM-dd HH:mm').format(accessory.datePublished!)}'
            : '';
        return ListTile(
          onTap: onTap,
          onLongPress: onLongPress,
          title: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              buildIcon(),
              buildIconMargin(),
              Text(
                accessory.name +
                    (accessory.isActive ? '' : ' (未激活)') +
                    dateString,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: accessory.isActive
                      ? Theme.of(context).colorScheme.onSurface
                      : Theme.of(context).disabledColor,
                ),
              )
            ],
          ),
          subtitle: Text(locationString),
          trailing: distance,
          dense: true,
          leading: AccessoryIcon(
            icon: accessory.icon,
            color: accessory.color,
          ),
        );
      },
    );
  }

  Widget buildIcon() {
    switch (accessory.lastBatteryStatus) {
      case AccessoryBatteryStatus.ok:
        return const Icon(Icons.battery_full, color: Colors.green, size: 15);
      case AccessoryBatteryStatus.medium:
        return const Icon(Icons.battery_3_bar, color: Colors.orange, size: 15);
      case AccessoryBatteryStatus.low:
        return const Icon(Icons.battery_1_bar, color: Colors.red, size: 15);
      case AccessoryBatteryStatus.criticalLow:
        return const Icon(Icons.battery_alert, color: Colors.red, size: 15);
      default:
        return const SizedBox(width: 0);
    }
  }
  
  Widget buildIconMargin() {
    switch (accessory.lastBatteryStatus) {
      case AccessoryBatteryStatus.ok:
      case AccessoryBatteryStatus.medium:
      case AccessoryBatteryStatus.low:
      case AccessoryBatteryStatus.criticalLow:
        return const SizedBox(width: 3);
      default:
        return const SizedBox(width: 0);
    }
  }
}
